package com.fyx.until;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.SetBucketCORSRequest;
import com.fyx.exception.MyException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

@Component
@Data
public class OSSUtil {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucketName}")
    private String bucketName;

    public static final String IMAGE_SUFFIX = "bmp,jpg,png,gif,jpeg";

    public String upload(MultipartFile multipartFile) throws IOException {

        if (isNull(multipartFile)) {
            throw new MyException("上传数据/地址获取异常");
        }
        //生成文件名
        String objectName = multipartFile.getOriginalFilename();
        int suffixLen = objectName.lastIndexOf(".");
        if (suffixLen == -1) {
            throw new MyException("文件获取异常");
        }
        String suffix = objectName.substring(suffixLen, objectName.length());
        objectName = UUID.randomUUID() + suffix;
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, objectName, multipartFile.getInputStream());
        // 关闭OSSClient。
        ossClient.shutdown();
        return "https://"+bucketName+"."+endpoint+"/"+objectName;
    }

    public void delete(String objectName){

        if (objectName == null || objectName == "") {
            throw new MyException("删除文件名不能为空");
        }

        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName,objectName);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    private boolean isNull(MultipartFile multipartFile) {
        if (null != multipartFile) {
            return false;
        }
        return true;
    }
}
